package com.flydog.taskManager.service.impl;

import com.flydog.taskManager.common.util.DateUtil;
import com.flydog.taskManager.dto.StatisticResult;
import com.flydog.taskManager.repository.PeriodicTaskRepository;
import com.flydog.taskManager.repository.PhasedTaskRepository;
import com.flydog.taskManager.security.config.SecurityUtil;
import com.flydog.taskManager.service.StatisticService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

@Service
@Slf4j
public class StatisticServiceImpl implements StatisticService {

    @Autowired
    PhasedTaskRepository phasedTaskRepository;

    @Autowired
    PeriodicTaskRepository periodicTaskRepository;

    @Autowired
    SecurityUtil securityUtil;
    @Override
    public StatisticResult CountOverview(Calendar date) {

        Calendar beginDate = DateUtil.initDateToStartTimeInDay(date);
        Calendar endDate = Calendar.getInstance();
        endDate.setTime(beginDate.getTime());
        DateUtil.initDateToEndTimeInDay(endDate);
        Long userId = securityUtil.getAuthUserId();
        int[] beginInDayCounts = new int[5];
        int[] endInDayCounts = new int[5];
        for (int dayAfter = 0; dayAfter < 5; dayAfter++) {
            beginInDayCounts[dayAfter] =
                    phasedTaskRepository.countByBeginBetweenAndUserId(beginDate, endDate, userId);

            int phaseEnd = phasedTaskRepository.countByEndBetweenAndUserId(beginDate, endDate, userId);
            int periodEnd = periodicTaskRepository.countByPeriodEndTimeBetweenAndUserId(beginDate, endDate, userId);

            endInDayCounts[dayAfter] = phaseEnd + periodEnd;
            beginDate.add(Calendar.DATE, 1);
            endDate.add(Calendar.DATE, 1);
        }
        StatisticResult result = new StatisticResult();
        result.setBeginToday(beginInDayCounts[0]);
        result.setEndToday(endInDayCounts[0]);
        result.setBeginIn3(Arrays.stream(beginInDayCounts).limit(3).sum());
        result.setEndIn3(Arrays.stream(endInDayCounts).limit(3).sum());
        result.setBeginIn5(Arrays.stream(beginInDayCounts).limit(5).sum());
        result.setEndIn5(Arrays.stream(endInDayCounts).limit(5).sum());
        return result;
    }
}
